package com.hdd.hll.quartz.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdd.hll.common.response.Result;
import com.hdd.hll.common.utils.AesEncryptUtils;
import com.hdd.hll.common.utils.OpenApiLogUtil;
import com.hdd.hll.modules.sendtruck.web.dto.PushStopTruckDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 取消派车推送Job实现类
 *
 * @author jw
 */
@Component
@Slf4j
public class PushStopTruckJob implements Job {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${jd.api.url}")
    private String jdApiUrl;

    @Value("${api.path.suffix.sendTruck.cancelDispatch}")
    private String cancelDispatch;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Map map = context.getJobDetail().getJobDataMap();
        Set<Map.Entry<String, String>> entrys = map.entrySet();
        for (Map.Entry<String, String> entry : entrys) {
            // 渠道参数，执行相应的业务流程
            log.info("执行JD调拨单信息同步接口推送任务，入参：{}", entry.getValue());
            pushTruckStop(JSON.parseObject(entry.getValue(), PushStopTruckDto.class));
        }
    }

    public Result<String> pushTruckStop(PushStopTruckDto pushStopTruckDto) {
        StringBuilder dataValidateResult = pushTruckStopParamValidRes(pushStopTruckDto);
        Result<String> result = new Result<>();
        if (!StringUtils.isBlank(dataValidateResult)) {
            result.setCode("301");
            result.setMsg(dataValidateResult.toString());
            OpenApiLogUtil.logResponse(result);
            return result;
        }
        Result<String> decryptResp = null;

        try {
            String vehicleReleaseEncryptRes = restTemplate.postForObject(jdApiUrl + cancelDispatch, AesEncryptUtils.encrypt(JSON.toJSONString(pushStopTruckDto)), String.class);
            decryptResp = JSONObject.parseObject(AesEncryptUtils.decrypt(vehicleReleaseEncryptRes), Result.class);
            log.info("请求JD矿区车辆派车取消接口，Msg：{}", decryptResp);
        } catch (Exception e) {
            log.error("请求JD矿区车辆派车取消接口异常，Msg：{}", e.getMessage());
            if (Objects.isNull(decryptResp)) {
                decryptResp = new Result();
            }
            decryptResp.setCode("500");
            decryptResp.setMsg(String.format("请求JD矿区车辆派车取消接口异常，Msg：%s", e.getMessage()));

        }

        OpenApiLogUtil.logResponse(decryptResp);
        return decryptResp;
    }

    private StringBuilder pushTruckStopParamValidRes(PushStopTruckDto pushStopTruckDto) {
        StringBuilder dataValidateResult = new StringBuilder();
        if (StringUtils.isBlank(pushStopTruckDto.getMiningDistrictId())) {
            dataValidateResult.append("获取矿区编码异常：miningDistrictId must not be null or empty;");
        }
        if (StringUtils.isBlank(pushStopTruckDto.getMiningDistrict())) {
            dataValidateResult.append("获取矿区名称异常：miningDistrict must not be null or empty;");
        }
        if (StringUtils.isBlank(pushStopTruckDto.getShipmentNo())) {
            dataValidateResult.append("获取派车单号异常：shipmentNo must not be null or empty;");
        }
        if (StringUtils.isBlank(pushStopTruckDto.getTimeoutTime())) {
            dataValidateResult.append("获取操作时间异常：timeoutTime must not be null or empty;");
        }
        if (StringUtils.isBlank(pushStopTruckDto.getVehicleLicense())) {
            dataValidateResult.append("获取车牌号异常：vehicleLicense must not be null or empty;");
        }
        if (Objects.isNull(pushStopTruckDto.getType())) {
            dataValidateResult.append("获取类型异常：type must not be null;");
        }

        return dataValidateResult;
    }
}
